local bs = $bs

local CSspec = "nic4"
	use "$working/CS_klme_`CSspec'", clear
	
	tempfile params
	save `params', replace

	use "$working/prowess_wits_estimation_qonly_klme.dta", clear

	generate mergeme = 1
	
	merge m:1 nic_08_4dig using `params'
	drop _merge

	tabulate nic_08_2dig, sort

	***Drop the single product firms that are non-comparable- i.e., missing energy and quantity data
	keep if q_s!=. &  energy_intensity!=.

	merge m:1 co_code1 year using "$working/first_last_years.dta"
	keep if _merge==3
	drop _merge

	sort product_id year
	xtset product_id year
	bys co_code1 year: egen nprod = count(co_code1)
	tsfill, full
	sort product_id year
	gen N = missing(L.co_code1)
	gen D = missing(f.co_code1)

	replace N = . if first_year == 1
	replace D = . if last_year == 1

	drop if missing(co_code1)

	drop cleaned_number_prod
	bysort co_code1 year: generate cleaned_number_prods = _N

	tabulate cleaned_number_prods

	gen omega_j= q_s - beta_l_hat_q * (l + ln_shares) - beta_k_hat_q* ( k + ln_shares) - beta_m_hat_q * (m + ln_shares) - beta_e_hat_q*(e + ln_shares)
	
	
	egen firm_prod = group(up12 co_code1)
	egen firm_year =  group(co_code1 year)

	merge 1:m year co_code1 product_name5 using "$tempfold/bssample1"
	keep if _merge==3
	drop _merge		
	
	ivreghdfe q_s (ln_price = omega_j), absorb(firm_prod firm_year) first cluster(co_code1)

	generate sample0 = e(sample)
	keep if sample0 == 1

	generate sigma_hat= _b[ln_price]	

	replace nic_08_2dig = "all"
	contract nic_08_2dig sigma_hat 
			
	rename _freq Observations
			
	local spec = "$spec"
	save "$tempfold/D_TFPQIV_CS_klme_nic4", replace

	collapse (mean) sigma_hat (sum) Observations

	generate bs = `bs'

	save "$tempfold/bs_D_TFPQIV_CS_klme_nic4", replace

clear
use "$BS_fold/bs_D_TFPQIV_CS_klme_nic4"
append using "$tempfold/bs_D_TFPQIV_CS_klme_nic4"
save  "$BS_fold/bs_D_TFPQIV_CS_klme_nic4", replace
